from django.shortcuts import render, redirect
from django.views.generic import ListView, UpdateView, DeleteView, CreateView, DetailView
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from ChanPin.models import Dingdan
from .models import KeHu, KeHuzilao, KeHugenjinlog
from .forms import KeHuForm, KeHuzilaoForm, KeHugenjinlogForm,KeHu_zhaungtaiForm
from django.urls import reverse
from ChanPin.forms import KeHuDingdanForm
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.db.models import Q


# from .forms import KeHuFormSet

# Create your views here.
@method_decorator(login_required, name='dispatch')
class kehulist(ListView):
    model = KeHu
    template_name = "kehu_list.html"
    context_object_name = 'kehu_list'
    bigtitle = "客户管理"
    paginate_by = 10
    ordering = ['addtime']  # 按照id降序排列

    def get_queryset(self):
        # 获取当前登录的用户
        current_user = self.request.user

        # 从GET请求中获取搜索词
        search = self.request.GET.get('search', '')

        # 获取原始的queryset
        #queryset = super().get_queryset()

        # 获取原始的queryset并基于当前用户进行过滤 同时判断是否是超级用户超级用户显示所有
        if current_user.is_superuser:
            return KeHu.objects.all()
        else:
            return KeHu.objects.filter(admin_user=current_user) # 过滤出当前用户的数据


        # 如果没有搜索词，则返回原始queryset
        if not search:
            return queryset

        # 使用Q对象构建复杂的查询条件
        search_query = Q(username__icontains=search) | Q(name__icontains=search) | Q(tel__icontains=search)
        # 根据搜索条件过滤queryset
        return queryset.filter(search_query)

    def get_context_data(self, **kwargs):
        # 获取上下文
        context = super().get_context_data(**kwargs)
        # 添加 bigtitle 和 搜索词 到上下文
        context['bigtitle'] = self.bigtitle
        context['search'] = self.request.GET.get('search', '')
        return context

@method_decorator(login_required, name='dispatch')
class KeHuCreateView(CreateView):
    model = KeHu
    form_class = KeHuForm
    template_name = 'kehu_add.html'
    success_url = reverse_lazy('kehu_list')


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if 'kehu_zhaungtai_form' not in context:
            context['kehu_zhaungtai_form'] = KeHu_zhaungtaiForm(self.request.POST or None)
        return context

    def form_valid(self, form):
        context = self.get_context_data()
        kehu_zhaungtai_form = context['kehu_zhaungtai_form']
        self.object = form.save()

        if kehu_zhaungtai_form.is_valid():
            kehu_zhaungtai_form.instance.kehu = self.object
            kehu_zhaungtai_form.save()

        return super().form_valid(form)



class KehuDeleteView(DeleteView):
    model = KeHu
    success_url = 'kehu_list'
    template_name = "kehu_del.html"


class KehuUpdateView(UpdateView):
    model = KeHu
    form_class = KeHuForm
    template_name = 'kehu_up.html'
    success_url = reverse_lazy('kehu_detail', kwargs={'pk': 1})  # 需要根据实际情况调整

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        kehu_obj = self.get_object()
        try:
            zilao_obj = kehu_obj.kehuzilao
            context['zilao_form'] = KeHuzilaoForm(instance=zilao_obj, prefix='zilao')
        except KeHuzilao.DoesNotExist:
            context['zilao_form'] = KeHuzilaoForm(prefix='zilao')
        return context

    def form_valid(self, form):
        response = super().form_valid(form)
        zilao_form = KeHuzilaoForm(self.request.POST, prefix='zilao', instance=self.object.kehuzilao)
        if zilao_form.is_valid():
            zilao_form.save()
        return response


class KeHuZilaoCreateOrUpdate(CreateView):
    model = KeHuzilao
    form_class = KeHuzilaoForm
    template_name = 'kehu_detail.html'
    success_url = reverse_lazy('kehu_detail', kwargs={'pk': 1})  # 需要根据实际情况调整

    def dispatch(self, request, *args, **kwargs):
        self.kehu = get_object_or_404(KeHu, pk=kwargs['pk'])
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        form.instance.kehu = self.kehu
        response = super().form_valid(form)
        return response


class KehuDetail(DetailView):
    """客户详情"""
    template_name = 'kehu_detail.html'
    extra_context = {'title': '客户信息详情'}
    model = KeHu
    context_object_name = 'khxq'
    bigtitle = "客户详情"


    def get(self, request, *args, **kwargs):
        self.object = self.get_object()# 获取当前客户对象
        print(f"Received POST data for {self.object}: {request}{request.GET}:{kwargs}")
        context = self.get_context_data(object=self.object)#初始化上下文将对象进行填充
        #################################原始代码，
        context['genjinlog_form'] = KeHugenjinlogForm()  # 添加空表单到上下文
        context['KeHuzilao_Form'] = KeHuzilaoForm()  # 添加空表单到上下文
     #   context['KeHu_Form'] = KeHuForm(instance=self.object)  # 添加空表单到上下文
        context['KeHuDingdan_Form'] = KeHuDingdanForm()  # 添加空表单到上下文

        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        form_key = request.POST.get('form_key')

        # 获取所有表单实例，注意为需要文件上传的表单添加 request.FILES
        forms = {
            'genjinlog': KeHugenjinlogForm(request.POST),
            'ziliao': KeHuzilaoForm(request.POST, request.FILES),
            # 添加 request.FILES 当字段是文件字段需要额外处理在forms 前端表单需要添加 enctype="multipart/form-data"
            #  'xinxi': KeHuForm(request.POST),
            'dingdan': KeHuDingdanForm(request.POST),
        }
        # 处理每个表单
        if form_key and form_key in forms:
            form = forms[form_key]
            print(f"Received POST data for {form_key}: {request.POST}:{kwargs}")
            if form.is_valid():
                instance = form.save(commit=False)
                if form_key == 'ziliao':
                    # 检查是否已经存在相关的 KeHuzilao 记录
                    try:
                        existing_instance = KeHuzilao.objects.get(kehu=self.object)
                    except KeHuzilao.DoesNotExist:
                        # 如果不存在，则创建一个新实例
                        instance = form.save(commit=False)
                    else:
                        # 如果存在，则更新现有实例
                        instance = existing_instance
                        instance.hujileixing = form.cleaned_data['hujileixing']
                        instance.hujizhenghao = form.cleaned_data['hujizhenghao']
                        # 如果 fujian 字段是可选的，并且您想要保留现有文件（如果未上传新文件）：
                        if 'fujian' in form.cleaned_data and form.cleaned_data['fujian']:
                            instance.fujian = form.cleaned_data['fujian']
                        # 注意：上面的代码片段需要您根据实际情况进行调整
                instance.kehu = self.object
                instance.save()
                form.save_m2m()  # 如果字段是多对多则需要调用这个方法保存多对多关系当 commit=False时，Django会延迟保存多对多关系，直到你显式地调用save_m2m()。


                redirect_url = reverse('Kehu_detail', kwargs={'pk': self.object.id})
                query_params = {
                    'genjinlog': '#v-pills-settings',
                    'ziliao': '#v-pills-xiangqing',
                   # 'xinxi': '#v-pills-home',
                    'dingdan': '#v-pills-profile',
                }.get(form_key, '#v-pills-home')
                full_url = f'{redirect_url}{query_params}'
                return redirect(full_url)
            else:
                # 表单验证失败，打印错误消息
                print(form.errors)
                # 如果没有表单通过验证，将所有表单传递给上下文
                context.update(forms)
                return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        kehu_obj = self.object
        # 添加当前客户的跟进记录列表到上下文
        genjinlogs = KeHugenjinlog.objects.filter(kehu=kehu_obj).order_by('-genjintime')  # 在KeHugenjinlog模型中查询kehu=kehu_obj的记录 .order_by('genjintime')默认为升序，加-为降序
        context['genjinlogs'] = genjinlogs
        kehuziliaos = KeHuzilao.objects.filter(kehu=kehu_obj)
        context['kehuziliaos'] = kehuziliaos
        kehuxinxis = KeHu.objects.filter(name=kehu_obj)
        context['kehuxinxis'] = kehuxinxis
        kehudingdans = Dingdan.objects.filter(kehu=kehu_obj)
        context['kehudingdans'] = kehudingdans
        return context


class genjinlogsDeleteView(DeleteView):
    model = KeHugenjinlog
    template_name = "KeHugenjinlog_del.html"
    context_object_name = 'log_entry'  # 可选，用于在模板中引用对象
    success_url_name = 'Kehu_detail'  # 用于反转的 URL 名称

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "确定删除这条跟进记录?"  # 直接在视图中设置标题
        return context

    def get_success_url(self):
        success_url = reverse(self.success_url_name, kwargs={'pk': self.object.kehu.id})
        query_params = '#v-pills-settings'
        return f'{success_url}{query_params}'

class kehudingdanDeleteView(DeleteView):
    model = Dingdan
    template_name = "dingdan_del.html"
    context_object_name = 'log_entry'  # 可选，用于在模板中引用对象
    success_url_name = 'Kehu_detail'  # 用于反转的 URL 名称

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "确定删除这条订单?"  # 直接在视图中设置标题
        return context

    def get_success_url(self):
        success_url = reverse(self.success_url_name, kwargs={'pk': self.object.kehu.id})
        query_params = '#v-pills-profile'
        return f'{success_url}{query_params}'